package top.lingkang.finalsql.utils;

import top.lingkang.finalsql.error.FinalException;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author lingkang
 * Created by 2022/5/3
 */
public class CommonUtils {
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isNull(Object obj) {
        return obj == null;
    }

    public static boolean notEmpty(Object... args) {
        return args != null && args.length != 0;
    }

    public static boolean isEmpty(Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }

    public static boolean isNotEmpty(CharSequence cs) {
        return !isEmpty(cs);
    }

    public static void close(AutoCloseable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                // 不做处理
            }
        }
    }


    public static int getFindNumber(String str, String findStr) {
        int index = 0;
        int has = 0;
        while ((index = str.indexOf(findStr, index)) != -1) {
            has++;
            index++;
        }
        return has;
    }

    public static void checkParam(String sql, List<Object> param) {
        checkParam(sql, param.toArray(new Object[0]));
    }

    /**
     * 检查参数是否正确
     */
    public static void checkParam(String sql, Object... param) {
        int findNumber = CommonUtils.getFindNumber(sql, "?");
        if (param == null && findNumber == 0)
            return;
        if (findNumber != param.length) {
            throw new FinalException(
                    "SQL入参 ? 个数与入参个数不匹配，请检查入参个数是否匹配。当前：?个数：" + findNumber + "  入参个数：" + param.length +
                            "\n sql: " + sql + " 入参：" + Arrays.toString(param)
            );
        }
    }

    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static int id = 0;

    public synchronized static int generatorId() {
        id++;
        return id;
    }
}
